<template>
  <el-container>
    <div style="padding: 10px;padding-bottom: 0">
      <div class="report_header" ref="headerHeight">
        <div style="display: flex;align-items: center;justify-content: space-between">
          <div class="report_header_left"></div>
          <div style="display: flex;align-items:flex-end;">
            <div class="report_header_date">
              <el-date-picker
                style="width: 100%"
                v-model="query.date"
                value-format="yyyy-MM-dd"
                type="daterange"
                align="right"
                unlink-panels
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                :picker-options="pickerOptions">
              </el-date-picker>
            </div>
            <div class="report_header_query">
             <el-select v-model="memberName" value-key="id" clearable placeholder="请选择客户"
                        filterable @focus="getMemberList" @change="selectMember" :filter-method="queryMember">
               <el-option v-for="item in memberIdOptions" style="width: 600px;" :key="item.id" :label="item.name"
                          :value="item">
                 <div style="display: flex">
                   <span style="width: 60px;">{{ item.code }}</span>
                   <span style="float: left;width: 100px;overflow: hidden;text-overflow: ellipsis;">{{
                     item.name
                     }}</span>
                   <span style="float: right; color: #8492a6; font-size: 8px;width: 80px;margin-left: 10px">{{
                     item.mobile
                     }}</span>
                   <div style="width: 200px;">
                     <span style="color: #8492a6; font-size: 8px;">{{ item.address }}</span>
                   </div>
                 </div>
               </el-option>
               <div style="display: flex;width: 100%;position: absolute;bottom: 0">
                 <div style="width: 50%;background-color: rgb(248,248,248);"></div>
                 <div class="elOption" @click="toSearchMember">搜索客户</div>
               </div>
               <div style="height: 30px"></div>
             </el-select>
            </div>

            <div class="report_header_query">
              <el-select  v-model="query.status" placeholder="请选择状态" clearable style="width: 100%">
                <el-option label="待领取" value="0"></el-option>
                <el-option label="待使用" value="1"></el-option>
                <el-option label="已使用" value="2"></el-option>
                <el-option label="已完成" value="3"></el-option>
                <el-option label="待激活" value="9"></el-option>
              </el-select>
            </div>


          </div>
          <div style="display: flex;flex-direction: row;justify-content: flex-end">

              <div class="report_header_query">
                <el-input
                  prefix-icon="el-icon-search"
                  placeholder="旅游卡号"
                  v-model="query.sn"
                  style="width: 100%"
                ></el-input>
              </div>

            <el-button style="margin-left: 10px;margin-top: 7px;height: 100%" size="small" type="primary" @click="queryClick">查询
            </el-button>
<!--            隐藏显示按钮-->
<!--            <div @click="chooseClick" style="width: 46px;height: 32px;background-color: #409EFF;margin-top: 7px;margin-left: 10px;border-radius: 4px;display: flex;justify-content: center;align-items: center;">-->
<!--              <i style="font-size: 24px;color: white;" :class="[queryType == false?'el-icon-caret-bottom':'el-icon-caret-top']"></i>-->
<!--            </div>-->
            <el-button style="margin-left: 10px;margin-top: 7px;height: 100%" size="small" type="primary" @click="publishClick"
                       v-permission="['touristCard.publish']">发卡
            </el-button>
            <ExportList2Excel style='margin-top: 5px;' ref="exportList2Excel" @handleExport="handleExport"  name="导出" />
          </div>
        </div>
        <div style="width: 800px;display: flex;align-items: center;" v-show="queryType == true">
<!--          这是放隐藏条件的容器-->
        </div>
      </div>
    </div>
    <div class="pd10">
      <div class="details_card" v-loadMore="[payLoads,'tourist-list']" :style="{height:curHeight+'px'}">
        <touristList :touristForm="touristForm" @detailsClick="detailsClick"></touristList>
      </div>
    </div>

    <el-footer class="el-footerBox" style="margin-bottom: auto">
      <pagination :total="total" :page.sync="pageNum" :limit.sync="pageSize"
                  @pagination="loadOrder"></pagination>
    </el-footer>


    <el-dialog
      title="发卡"
      :visible.sync="publishVisible"
      width="40%"
      v-el-drag-dialog
      append-to-body
      :before-close="publishClose">
      <div style="position: relative;">
        <el-form ref="publishForm"  :model="publishForm" rules="rules" label-width="90px">
          <el-row :gutter="24" class="deleted_OrderContent">
            <el-col :span="24">
              <el-form-item label="旅游线路:" :prop="'productName'" :rules="rules.productName">
                 <el-select v-model="publishForm.productName" filterable placeholder="请选择"  remote :remote-method="productMethod" @change="selectClick">
                  <el-option
                    v-for="(item,index) in listForm"
                    :key="index"
                    style="width:450px"
                    :label="item.name"
                    :value="index"
                  >
                    <div style="display: flex">
                      <span style="width: 120px;overflow: hidden;text-overflow: ellipsis;">{{ item.sn }}</span>
                      <span style="float: left;width: 200px;overflow: hidden;text-overflow: ellipsis;margin-left: 10px">{{ item.name }}</span>
                      <div style="width: 120px;">
                        <span style="color: #8492a6; font-size: 8px;">{{item.spec1}}</span>
                      </div>
                    </div>
                  </el-option>
                  <div style="display: flex;width: 100%;position: absolute;bottom: 0">
                    <div style="width: 50%;background-color: rgb(248,248,248);"></div>
                    <!-- <div class="elOption" @click="toAddProduct">搜索商品</div> -->
                    <!-- <div class="elOption1" @click="toSearchProduct">新增商品</div> -->
                  </div>
                  <div style="height: 30px"></div>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="24" class="deleted_OrderContent">
            <el-col :span="24">
              <el-form-item label="数量:" :prop="'publishQty'" :rules="rules.publishQty">
                 <el-input v-model="publishForm.publishQty" type="text" placeholder="请输入数量"/>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="24" class="deleted_OrderContent">
            <el-col :span="24">
              <el-form-item label="备注:">
                 <el-input v-model="publishForm.memo" type="text" placeholder="请输入备注"/>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <div style="
            display: flex;
            justify-content:space-between;
            align-items: center;
            margin-top: 30px;
            margin-left: 100px;
          ">
          <el-button type="primary" :loading="publishSaveClick" @click="publichSave">保存</el-button>
        </div>

      </div>
    </el-dialog>
  </el-container>
</template>

<script>
import { EventBus } from '@/api/eventBus'
import memberTable from '@/components/MemberTable/index'
import touristList from './components/list'
import { list as memberList } from '@/api/member'
import { list, publishCard } from '@/api/tourist'
import {list as productList} from '@/api/product'
import elDragDialog from '@/directive/el-drag-dialog' // base on element-ui
import Pagination from '@/components/Pagination'
import utils from '../../utils/utils.js'
import loadMore from '@/utils/more.js'
import permission from '@/directive/permission/index.js' // 权限判断指令
import ExportList2Excel from "@/components/ExportList2Excel";
export default {
  name: 'touristCard-list',
  directives: { loadMore, permission, elDragDialog },
  activated() {
    this.payLoads = new Date().getTime()
  },
  data() {
    return {
      payLoads: '',
      touristForm: [],
      memberIdOptions: [],
      employee: [],
      listForm: [],
      times: '',
      memberName: '',
      pageNum: 1,
      pageSize: 20,
      queryClicked: false,
      publishSaveClick: false,
      saveClicked: false,
      publishVisible: false,
      total: 0,
      curHeight: null,
      queryType: false,
      printing:7000,
      publishForm: {
        productId: '',
        productName: '',
        productSn:'',
        thumbnail:'',
        price: '',
        marketPrice: '',
        cardType:'1',
        validStartDate: '',
        validEndDate:'',
        publishQty: 1
      },
      query: {
        memberId: '',
        date: [],
        status: '',
        sn: '',
      },
      keyword: {
        memberId: '',
        date: [],
        status: '',
        sn: ''
      },
      pickerOptions: {//时间快捷选择
        shortcuts: [{
          text: '昨天',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近一周',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
            picker.$emit('pick', [start, end])
          }
        }]
      },
      rules: {
          productName: [
            { required: true, message: '请选择旅游线路', trigger: 'blur' }
          ],
          publishQty: [
            { required: true, message: '请填写数量', trigger: 'blur' }
          ]
        }
    }
  },
  components: {
    Pagination, touristList,memberTable,ExportList2Excel
  },
  filters:{
    watchType(val){
      if (val==1){
        return '领用单';
      }
    }
  },
  created() {
    var _this = this;
    this.loadOrder();
    EventBus.$on('touristCard-add', res => { // 监听新增完毕
      // 更新列表数组
      _this.touristForm.splice(0, 0, res)
    })
    EventBus.$on('touristCard-edit', res => { // 监听状态更新
      // 更新列表数组
      for (var i = 0; i < _this.touristForm.length; i++) {
        if (_this.touristForm[i].id == res.id) {
          _this.$set(this.touristForm, i, res)
        }
      }
    })
    EventBus.$on('touristCard-delete', res => { // 监听订单删除
      // 更新列表数组
      /* for (var i = 0; i < _this.orderForm.length; i++) {
        if (_this.orderForm[i].id == res.id) {
          _this.orderForm.splice(i,1)
          return;
        }
      } */
      this.loadOrder()
    })
    EventBus.$on('touristCard-view', res => { // 监听订单删除
      // 更新列表数组
      for (var i = 0; i < _this.touristForm.length; i++) {
        if (_this.touristForm[i].id == res.id) {
          _this.$set(this.touristForm, i, res)
        }
      }
    })
  },
  mounted() {
    this.comeIn()
    this.beforeMount()
  },
  methods: {
    queryMember(query) { // 搜索客户
      console.log(query)
      this.memberIdOptions = []
      memberList({ keyword: query }).then(res => {
        res.data.data.forEach((option, index) => {
          this.$set(this.memberIdOptions, index, option)
        })
      }).catch(err => {
        console.log(err)
      })
    },
    getMemberList() { // 加载客户
      memberList().then(res => {
        res.data.data.forEach((option, index) => {
          this.$set(this.memberIdOptions, index, option)
        })
      }).catch(err => {
        console.log(err)
      })
    },
    toSearchMember() {
      this.memberTableVisible = true
    },
    selectMember(data) {
      if (!utils.isNull(data)){
        this.memberName = data.name
        this.query.memberId = data.id
      }else {
        this.query.memberId = ''
      }

    },
    beforeMount() {
      var _this = this
      window.onresize = () => {
        return (() => {
          if (_this.queryType == false) {
            var h = document.documentElement.clientHeight || document.body.clientHeight
            _this.curHeight = h - 265//减去页面上固定高度height
          } else {
            var h = document.documentElement.clientHeight || document.body.clientHeight
            _this.curHeight = h - 224//减去页面上固定高度height
          }
        })()
      }
    },
    comeIn() {
      var h = document.documentElement.clientHeight || document.body.clientHeight
      this.curHeight = h - 224//减去页面上固定高度height
    },
    loadOrder() {
      var _this = this
      if (utils.isNull(this.query.date)){
        this.query.date = []
      }
      let params = new URLSearchParams()
      params.append('pageNum', _this.pageNum)
      params.append('pageSize', _this.pageSize)
      params.append('status', this.query.status)
      params.append('sn', this.query.sn)
      params.append('memberId', this.query.memberId)
      params.append('startDate', this.query.date.length > 0 ? this.query.date[0] : '')
      params.append('endDate', this.query.date.length > 0 ? this.query.date[1] : '')

      list(params).then(response => {
        _this.touristForm = response.data.data
        _this.total = response.data.total
      }).catch(error => {
        console.log('error!!')
      })
    },
    chooseClick() {
      this.queryType = !this.queryType
      if (this.queryType == true) {
        var h = document.documentElement.clientHeight || document.body.clientHeight
        this.curHeight = h - 265//减去页面上固定高度height
      } else {
        var h = document.documentElement.clientHeight || document.body.clientHeight
        this.curHeight = h - 224//减去页面上固定高度height
      }
    },
    queryClick() {
      this.queryClicked = true
      setTimeout(() => {
        this.queryClicked = false
      }, 300)
      this.keyword = this.query
      this.pageNum = 1
      this.loadOrder()
    },
    resetClick() {
      this.query.date = []
      this.productName = ''
      this.supplierName = ''
      this.query.sn = ''
      this.query.supplierId = ''
      this.query.productId = ''
      this.query.status = '',
        this.keyword = this.query
      this.pageNum = 1
      this.loadOrder()
    },
    detailsClick(data) {
      this.$router.push({
        path: '/tourist/view', query: { id: data }
      })
    },
    publishClick() {
      this.loadlist();
      this.publishVisible = true;
      /*this.$router.push({
        path: '/touristCard/add'
      })*/
    },

    changeDelivery(val){
      this.query.memberId = val;
    },
          //商品总数据
    loadlist(query) {
      var _this = this
      let params = new URLSearchParams();
      // params.append('keyword',query)
      params.append('sn', _this.keyword.sn)
      productList(params).then(response => {
        console.log(response);
        _this.listForm = response.data.data
      }).catch(error => {
        console.log('error!!')
      });
    },
    productMethod(query){
        this.loadlist(query)
    },
          //商品表下拉选择
    selectClick(index) {
      var _this = this
      if (index == '#') {
        _this.procuctVisible = true;
      } else if(index=='/'){
        this.orderVisible = true;
      } else {
        _this.publishForm.productId = _this.listForm[index].id;
        _this.publishForm.productName = _this.listForm[index].name;
        _this.publishForm.productSn = _this.listForm[index].sn;
        _this.publishForm.price = _this.listForm[index].price;
        _this.publishForm.marketPrice = _this.listForm[index].marketPrice;
        _this.publishForm.thumbnail = _this.listForm[index].thumbnail;
      }
    },
    publichSave(){
      var _this = this;
      _this.$refs.publishForm.validate((valid)=>{
        if (valid) { // 校验表单
          this.$confirm('是否发卡？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            this.publichSaveClicked = true;

            publishCard(this.publishForm).then(res => {
              _this.publichSaveClicked = false;
              _this.publishClose();
              _this.loadOrder();
              _this.publishForm = {};
              // EventBus.$emit('touristCard-add', res.data);
            }).catch(() => { this.publichSaveClicked = false })
          });
        }
      });

    },
    publishClose(){
      this.publishVisible = false;
    },
    handleDownload() {
      this.$router.push({
        path: "/touristCard/memberExport"
      })
    },
    handleExport() {
      let _this= this
      var  loading = this.$loading({
        lock: true,
        text: 'Loading',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });
      //要导出函数携带的参数
      //要导出函数携带的参数
      let data ={}
      data.tHeader = ["旅游卡名称","卡号","密码","金额","开始日期","结束日期","生成日期"]
      data.filterVal = ["productName","sn","password","price","validStartDate","validEndDate","createDate"]
      data.filename = "旅游卡列表";
      const params = new URLSearchParams()
      params.append('pageNum', _this.pageNum)
      params.append('pageSize', _this.printing)
      params.append('status', _this.query.status)
      params.append('sn', _this.query.sn)
      params.append('memberId', _this.query.memberId)
      params.append('startDate', _this.query.date.length > 0 ? this.query.date[0] : '')
      params.append('endDate', _this.query.date.length > 0 ? this.query.date[1] : '')
      list(params).then(res=>{
         //_this.memberData = response.data.data
        data.list=res.data.data
        data.list.forEach(item=>{
          item.createDate=utils.dateFormatter(item.createDate);
          item.validStartDate=utils.dateFormatter(item.validStartDate);
          item.validEndDate=utils.dateFormatter(item.validEndDate);
          })
       console.log(data.list);
       _this.$refs.exportList2Excel.handleDownload(data);
           loading.close();
        if(data.list.length==this.printing){
          this.pageNum++
           this.handleExport()
        }
        else{
          return;
        }
      }).catch(error=>{
        _this.$refs.exportList2Excel.unlockLoading()
        loading.close();
        console.log('error!!')
      })
    },


  }
}
</script>

<style scoped>
.details_card {
  overflow: auto;
  padding-left: 20px;
  padding-right: 20px;
  box-sizing: border-box;
  border: 1px solid #f2f2f2;
  border-radius: 4px;
}

.elOption {
  background-color: #909399;
  color: white;
  text-align: center;
  display: flex;
  align-items: center;
  justify-content: center;
  width: 50%;
  height: 40px
}

.details_card:hover {
  box-shadow: 0 2px 4px rgba(0, 0, 0, .12), 0 0 6px rgba(0, 0, 0, .04)
}

.el-input__inner {
  width: 100% !important;
}

.app {
  background-color: rgba(248, 248, 248, 0.8);
}

/deep/ .el-header {
  padding: 10px;
  /* height: 100% !important; */
  padding-bottom: 0;
}

.report_header {
  width: 100%;
  min-height: 40px;
  box-sizing: border-box;
  background-color: rgba(248, 248, 248, 0.8);
  display: flex;
  padding-bottom: 5px;
  position: relative;
  padding-left: 5px;
  padding-right: 5px;
  flex-direction: column;
}

.report_header_left {
  width: 5px;
  height: 46px;
  background-color: #409EFF;
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
}

.report_header_query {
  margin-left: 10px;
  /* width: 180px; */
  margin-top: 5px;
}

.report_header_date {
  margin-left: 10px;
  width: 250px;
  margin-top: 5px;
}
</style>
